<template>
  <div>
    <tabs :tabs="tabs" />
    <div class="paper">
      <div class="question-paper">
        <el-scrollbar class="paper-scrollbar">
          <div class="total-wrap">
            <div class="item">基本信息</div>
            <draggable v-model="parts" @end="draggingSort">
              <div v-for="(item, index) in parts" :key="index" class="item" @click="scrollAnchor(index)">第{{ paper[index] }}部分</div>
            </draggable>
            <div class="item add-item" @click="addPortion">+ 添加部分</div>
          </div>
          <div class="total-score">
            <div class="count">总题数：{{ topicsTotalCount }}道</div>
          </div>
          <el-divider />
          <el-row type="flex" class="total-info">
            <label class="label">考试时长：</label>
            <div class="default">
              <div class="text">
                <el-input-number v-model="baseInfo.total_time" controls-position="right" size="mini" :min="0" :max="200" />
                分钟
                <p>0表示不限制</p>
              </div>
              <div class="margin30"><el-button type="primary" size="mini" :disabled="disabledSubmit" @click="submit">保存</el-button></div>
            </div>
          </el-row>
        </el-scrollbar>
      </div>

      <div class="paper-wrap">
        <div class="item">
          <div class="title">基本信息</div>
          <el-form ref="baseInfoForm" :model="baseInfo" :rules="baseInfoRule" label-width="110px" size="mini">
            <el-form-item label="试卷名称" prop="title"><el-input v-model="baseInfo.title" placeholder="请输入内容" maxlength="30" show-word-limit /></el-form-item>
            <el-form-item label="试卷简介" prop="info">
              <el-input v-model="baseInfo.info" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入内容" maxlength="100" show-word-limit />
            </el-form-item>
            <el-form-item label="试卷分类" prop="cate">
              <el-cascader v-model="baseInfo.cate" :options="cateOptions" :props="{ expandTrigger: 'hover' }" @change="handleChange" @visible-change="cascaderFocus($event)" />
            </el-form-item>
            <!--<el-form-item label="考试时间">-->
            <!--  <el-date-picker-->
            <!--    v-model="baseInfo.exam_time"-->
            <!--    type="datetimerange"-->
            <!--    value-format="yyyy-MM-dd HH:mm:ss"-->
            <!--    range-separator="至"-->
            <!--    start-placeholder="开始日期"-->
            <!--    end-placeholder="结束日期"-->
            <!--  />-->
            <!--</el-form-item>-->
            <!--<el-form-item>-->
            <!--  <template v-slot:label>-->
            <!--    <span>考试次数</span>-->
            <!--    <el-popover trigger="hover" transition="el-zoom-in-bottom" placement="top" popper-class="popper">-->
            <!--      <div>0表示不限制考试次数</div>-->
            <!--      <template v-slot:reference>-->
            <!--        <i class="edu-icon-info" />-->
            <!--      </template>-->
            <!--    </el-popover>-->
            <!--  </template>-->
            <!--  <el-input-number v-model="baseInfo.exam_number" controls-position="right" :min="0" size="mini" />-->
            <!--</el-form-item>-->
            <el-form-item label="乱序设置"><el-checkbox v-model="baseInfo.answer_options_rand" :true-label="1" :false-label="0">选项乱序</el-checkbox></el-form-item>
            <el-form-item label="交卷后显示答案"><el-switch v-model="baseInfo.visible_answer" :active-value="1" :inactive-value="0" /></el-form-item>
            <el-form-item label="阅卷讲师"><search-teacher :value.sync="baseInfo.reviewer" :args="searchTeacherArgs" :form-datas="baseInfo" /></el-form-item>
          </el-form>
        </div>

        <div v-for="(part, partIndex) in parts" :id="'section' + partIndex" :key="partIndex" class="paper-item">
          <el-row type="flex" justify="space-between" align="middle" class="header">
            <div class="title">第{{ paper[partIndex] }}部分</div>
            <el-button icon="el-icon-delete" plain size="mini" @click="removePortion(partIndex)">移除该部分</el-button>
          </el-row>
          <el-form :model="part.form" label-width="80px" size="mini">
            <el-form-item label="名称">
              <el-row>
                <el-col :span="12"><el-input v-model="part.form.title" placeholder="请输入内容" maxlength="20" show-word-limit /></el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="答案说明">
              <el-input v-model="part.form.description" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入内容" maxlength="100" show-word-limit />
            </el-form-item>
          </el-form>
          <div class="question-wrap">
            <el-collapse v-model="partIds" class="question-collapse">
              <el-collapse-item title="试题详情" :name="partIndex">
                <el-row type="flex" align="middle" justify="space-between" class="info-wrap">
                  <el-row type="flex" align="middle">
                    <el-button icon="el-icon-delete" plain size="mini" class="btn-margin-right" @click="removeBankAll(partIndex)">移除</el-button>
                    <setting-scores :scores.sync="part.scores" />
                  </el-row>
                  <el-row type="flex" align="middle">
                    <div class="text">
                      共有{{ statisticScore(partIndex, 2) }}道题， 其中{{ statisticScore(partIndex, 1, 1) }}道单选题、 {{ statisticScore(partIndex, 1, 2) }}道判断题、
                      {{ statisticScore(partIndex, 1, 3) }}道多选题、 {{ statisticScore(partIndex, 1, 4) }}道不定项选择题、 {{ statisticScore(partIndex, 1, 5) }}道填空题、
                      {{ statisticScore(partIndex, 1, 6) }}道材料题、 {{ statisticScore(partIndex, 1, 7) }}道完形填空题、 {{ statisticScore(partIndex, 1, 8) }}道简答题
                    </div>
                    <el-button icon="el-icon-plus" type="primary" size="mini" @click="chooseBank(partIndex)">选择题库</el-button>
                  </el-row>
                </el-row>
                <el-table :key="Math.random()" :data="part.banks" style="width: 100%" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="45" />
                  <el-table-column label="题库">
                    <template slot-scope="scope">
                      {{ scope.row.title }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      单选题
                      <br>
                      每题分值: {{ part.scores.question_type_1 }}
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_1" controls-position="right" :min="0" :max="scope.row.question_counts[1] || 0" size="mini" />
                      /{{ scope.row.question_counts[1] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      判断题
                      <br>
                      每题分值: {{ part.scores.question_type_2 }}
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_2" controls-position="right" :min="0" :max="scope.row.question_counts[2] || 0" size="mini" />
                      /{{ scope.row.question_counts[2] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      多选题
                      <br>
                      每题分值: {{ part.scores.question_type_3 }}
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_3" controls-position="right" :min="0" :max="scope.row.question_counts[3] || 0" size="mini" />
                      /{{ scope.row.question_counts[3] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      不定项选择题
                      <br>
                      每题分值: {{ part.scores.question_type_4 }}
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_4" controls-position="right" :min="0" :max="scope.row.question_counts[4] || 0" size="mini" />
                      /{{ scope.row.question_counts[4] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      填空题
                      <br>
                      每题分值: --
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_5" controls-position="right" :min="0" :max="scope.row.question_counts[5] || 0" size="mini" />
                      /{{ scope.row.question_counts[5] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      材料题
                      <br>
                      每题分值:--
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_6" controls-position="right" :min="0" :max="scope.row.question_counts[6] || 0" size="mini" />
                      /{{ scope.row.question_counts[6] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      完形填空题
                      <br>
                      每题分值:--
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_7" controls-position="right" :min="0" :max="scope.row.question_counts[7] || 0" size="mini" />
                      /{{ scope.row.question_counts[7] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column>
                    <template slot="header">
                      简答题
                      <br>
                      每题: {{ part.scores.question_type_8 }}
                    </template>
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.topics.question_type_8" controls-position="right" :min="0" :max="scope.row.question_counts[8] || 0" size="mini" />
                      /{{ scope.row.question_counts[8] || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="90">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" @click="setTopicsMaxCount(scope)">全选</el-button>
                      <el-button size="mini" type="text" @click="removeBank(partIndex, scope.row.id)">移出</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
        <el-row type="flex" justify="center"><el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addPortion">添加部分</el-button></el-row>
      </div>
    </div>
    <choose-bank v-if="chooseTopicVisible" :part-index="currentPart" :cate-ids="cateIdsStr" @close="chooseTopicVisible = false" />
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import Tabs from '../tabs';
import SettingScores from '../setting/score.vue';
import ChooseBank from '../../question/bank/choose/select.vue';
import SearchTeacher from '@/pages/user/teacher/choose/index.vue';
import { mapGetters } from 'vuex';
/** 累加器 **/
const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0);
export default {
  components: {
    draggable,
    Tabs,
    SettingScores,
    ChooseBank,
    SearchTeacher
  },
  inject: ['reload'],
  data() {
    return {
      tabs: [
        {
          title: '新建随机试卷',
          uri: '/exam/paper/random/create',
          meta: {
            permission: 'exam.paper.create'
          }
        }
      ],
      // 试卷基本信息
      baseInfo: {
        title: '',
        info: '',
        cate: '',
        // exam_time: ['', ''],
        // exam_number: 0,
        question_rand: 0,
        answer_options_rand: 0,
        visible_answer: 0,
        total_time: 0, // 考试总时长
        reviewer: '' // 阅卷讲师
      },
      searchTeacherArgs: {
        mhm_id: 0
      },
      // 控制显示选择试题
      chooseTopicVisible: false,
      paper: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'],
      cateOptions: [],
      currentPart: 0,
      baseInfoRule: {
        title: [{ required: true, message: '试卷名称必须填写', trigger: ['blur', 'change'] }],
        info: [{ required: true, message: '试卷简介必须填写', trigger: ['blur', 'change'] }],
        cate: [{ required: true, message: '请选择试卷分类', trigger: ['blur', 'change'] }]
      },
      // 禁用提交按钮
      disabledSubmit: false,
      selectedBank: [] // checkbox选中的题库
    };
  },
  computed: {
    ...mapGetters({
      parts: 'examPaper/random/parts',
      topicsTotalCount: 'examPaper/random/topicsTotalCount',
      topicsTotalScore: 'examPaper/random/topicsTotalScore'
    }),
    partIds() {
      const parts = this.parts;
      const indexs = [];
      parts.forEach(function(item, index) {
        indexs.push(index);
      });

      return indexs;
    }
  },
  created() {
    // 先清空内容
    this.$store.dispatch('examPaper/random/clearParts');
    // 获取页面内容
    this.$http.get(
      '/exam/admin/paper/create',
      {},
      response => {
        const {
          data: { category, mhm_id: mhmId }
        } = response;
        this.cateOptions = category;
        this.$set(this.searchTeacherArgs, 'mhm_id', mhmId);
      },
      _ => {}
    );
  },
  destroyed() {
    this.$store.dispatch('examPaper/random/clearParts');
  },
  methods: {
    // 添加
    addPortion() {
      if (this.parts.length >= 20) {
        this.$message.warning('最多支持添加20个部分');
        return false;
      }
      // 新增部分
      this.$store.dispatch('examPaper/random/addPart');
    },
    cascaderFocus: function(e) {
      // 检查是否已绑定题库
      const exist = this.parts.some(part => part.banks.length);
      if (e && exist) {
        // this.$box
        //   .confirm('确定要移除题目吗？')
        //   .then(() => {
        //     this.$store.dispatch('examPaper/settled/removeTopicAll', { partIndex, topic });
        //   })
        //   .catch(() => {});
        this.$message.warning('切换分类前请移除所有题库');
      }
    },
    handleChange: function(value) {
      this.baseInfo.cate = value;
      this.cateIdsStr = ',' + value.join(',') + ',';
      // console.log(this.cateIdsStr);
    },
    // 删除
    removePortion(index) {
      if (this.parts.length > 1) {
        this.$box
          .confirm('确认要删除改选项吗')
          .then(() => {
            this.$store.dispatch('examPaper/random/removePart', index);
          })
          .catch(() => {});
      }
    },
    // 拖动
    draggingSort(e) {
      this.$store.dispatch('examPaper/random/movePart', {
        oldIndex: e.oldIndex,
        newIndex: e.newIndex
      });
    },
    // 锚点
    scrollAnchor(index) {
      document.getElementById('section' + index).scrollIntoView({ block: 'center', behavior: 'smooth' });
    },
    // 显示试题选择
    chooseBank(index) {
      if (this.baseInfo.cate && this.baseInfo.cate.length) {
        this.chooseTopicVisible = true;
        this.currentPart = index;
      } else {
        this.$message.error('请先选择试卷分类');
      }
    },
    // 移除试题
    removeBank(partIndex, bankId) {
      this.$box
        .confirm('确定要移除该题目吗？')
        .then(() => {
          this.$store.dispatch('examPaper/random/removeBank', {
            partIndex,
            bankId
          });
        })
        .catch(() => {});
    },
    // 设置全选试题
    setTopicsMaxCount({ row }) {
      const { question_counts: questionCounts, topics } = row;
      Object.keys(questionCounts).forEach(key => {
        topics['question_type_' + key] = questionCounts[key];
      });

      this.$set(row, 'topics', topics);
    },
    // 批量移除题库
    removeBankAll(partIndex) {
      const bank = this.selectedBank;
      if (bank.length === 0) {
        this.$message.error('请选择要移除的题库');
      } else {
        this.$box
          .confirm('确定要移除题库吗？')
          .then(() => {
            this.$store.dispatch('examPaper/random/removeBankAll', { partIndex, bank });
          })
          .catch(() => {});
      }
    },
    // 批量选中的试题数据
    handleSelectionChange(val) {
      this.selectedBank = val;
    },
    // 当前部分试题统计
    statisticScore(partIndex, states = 1, type) {
      /**
       * partIndex 当前部分下标
       * states 1当前部分每种题型的总题数，2当前部分的总题数
       * type 试题的类型
       */
      const data = this.parts[partIndex].banks;
      const statusMap = {
        1: sum(
          data.map(item => {
            const topics = {
              1: item.topics.question_type_1,
              2: item.topics.question_type_2,
              3: item.topics.question_type_3,
              4: item.topics.question_type_4,
              5: item.topics.question_type_5,
              6: item.topics.question_type_6,
              7: item.topics.question_type_7,
              8: item.topics.question_type_8
            };
            return topics[type];
          })
        ),
        2: sum(
          data.map(item => {
            let num = 0;
            for (const k in item.topics) {
              num += item.topics[k];
            }
            return num;
          })
        )
      };
      return statusMap[states];
    },
    submit() {
      // 验证
      this.$refs.baseInfoForm.validate(valid => {
        if (valid) {
          this.disabledSubmit = true;
          const data = {
            ...this.baseInfo,
            parts: this.$store.getters['examPaper/random/partsSubmitData']
          };
          this.$http.post(
            '/exam/admin/paper/random/create',
            data,
            response => {
              this.disabledSubmit = false;
              this.$message.success(response.msg, _ => {
                this.$store.dispatch('examPaper/random/clearParts');
                this.reload();
              });
            },
            error => {
              this.disabledSubmit = false;
              this.$message.error(error.msg);
            }
          );
        } else {
          this.$message.warning('请完善试卷基本信息');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.paper {
  position: relative;
  padding-top: 18px;
  padding-right: 50px;
  padding-bottom: 50px;

  .paper-scrollbar{
    height: 724px;
  }

  ::v-deep.el-input-number {
    width: 64px;
    line-height: 26px;
    &.is-controls-right .el-input__inner {
      padding-left: 5px;
      padding-right: 35px;
    }
  }
  .question-paper {
    width: 250px;
    box-sizing: border-box;
    padding: 12px 13px;
    border: 1px solid #e4e7ed;
    position: fixed;
    z-index: 99;
    background-color: #fff;
    .total-wrap {
      .item {
        box-sizing: border-box;
        height: 32px;
        line-height: 32px;
        background-color: #ececec;
        margin-bottom: 10px;
        text-align: center;
        cursor: pointer;
        font-size: 13px;
        font-weight: 400;
        color: #303133;
      }
      .add-item {
        border: 1px solid #5191ff;
        background-color: #fff;
        color: #5191ff;
      }
    }
    .total-score {
      margin-top: 22px;
      .count {
        font-size: 13px;
        font-weight: 400;
        color: #606266;
        & + .count {
          margin-top: 14px;
        }
      }
    }
    .total-info {
      .label {
        font-size: 13px;
        font-weight: 400;
        color: #606266;
      }
      .default {
        flex: 1;
      }
      .margin5 {
        margin-top: 5px;
      }
      .margin30 {
        margin-top: 30px;
      }
      .text {
        font-size: 12px;
        font-weight: 400;
        color: #606266;
      }
      ::v-deep.el-radio__label {
        font-size: 12px;
      }
    }
  }
  .paper-wrap {
    margin-left: 278px;
    .paper-item {
      padding: 12px 20px;
      margin-bottom: 21px;
      background-color: #f7f7f7;
      border: 1px solid #e4e7ed;
      .header {
        height: 36px;
        padding-right: 18px;
        margin: -12px -20px 30px;
        background-color: #e5e5e5;
        .title {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
          padding-left: 10px;
          position: relative;
          &::after {
            content: '';
            display: block;
            position: absolute;
            left: 0;
            top: 50%;
            margin-top: -7px;
            height: 14px;
            background-color: #5191ff;
            width: 2px;
          }
        }
      }
    }
    .question-wrap {
      padding: 0 15px;
      background: #ffffff;
      border: 1px solid #dcdfe6;
      ::v-deep.question-collapse {
        border: none;
        .el-collapse-item:last-child {
          margin-bottom: 0;
        }
        .el-collapse-item__header {
          border: none;
          position: relative;
          padding-left: 24px;
          .el-collapse-item__arrow {
            position: absolute;
            left: 0;
          }
        }
        .el-collapse-item__wrap {
          border: none;
        }
      }
      .info-wrap {
        .btn-margin-right {
          margin-right: 10px;
        }
        .text {
          width: 525px;
          font-size: 13px;
          font-weight: 400;
          color: #606266;
          line-height: 20px;
          margin-right: 10px;
          text-align: right;
        }
      }
      ::v-deep.table-collapse {
        border: none;
        .el-collapse-item:last-child {
          margin-bottom: 0;
        }
        .el-collapse-item__wrap {
          border: none;
        }
        .el-collapse-item__header {
          padding-left: 0;
          align-items: flex-start;
          flex-direction: column;
          height: auto;
          line-height: 16px;
          background-color: transparent;
          color: #606266;
          border-bottom: none;
          font-size: 12px;
        }
        .el-collapse-item__arrow {
          top: 1px;
          transform: rotate(90deg);
          color: #5191ff;
          &::before {
            content: '\e6dc';
          }
          &.is-active {
            transform: rotate(270deg);
          }
        }
        .el-collapse-item__wrap {
          background-color: transparent;
        }
        .el-collapse-item__content {
          color: #606266;
          font-size: 12px;
        }
      }
      .ques-title {
        padding-left: 24px;
        .number {
          color: #5191ff;
          margin-right: 10px;
        }
      }
      .ques-content {
        margin-top: 10px;
      }
      .ques-option {
        margin-top: 10px;
        .item {
          margin-bottom: 5px;
        }
      }
    }
  }
}
.edu-icon-info {
  cursor: help;
  margin-left: 2px;
}
</style>
